package day2;

public class Solution {
    public static void main(String[] args) {
        System.out.println(truncateSentence("Hello how are you Contestant", 4));
    }

    /**
     *截断句子
     * @param s
     * @param k
     * @return
     */
        public static String truncateSentence1(String s, int k) {
            if(s == null || s.equals("")||k <= 0 || k > s.length()){
                return null;
            }
            String[] arr = s.split(" ");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < k; i++) {
               sb.append(arr[i]);
               sb.append("");
            }
            return sb.toString().trim();
        }

    public static String truncateSentence(String s, int k) {
        if(s == null || s.equals("")||k <= 0 || k > s.length()){
            return null;
        }

        int count = 0;
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == ' '){
                count++;
                if(count == k){
                    return s.substring(0,i);
                }
            }
        }
        return s;
    }

    /**
     * 删除重复项
     * @param nums
     * @return
     */
    public int removeDuplicates(int[] nums) {
        int left = 0;
        int right = 1;
        while(right < nums.length){
            if(nums[left] == nums[right]){
                right++;
            }else{
                left++;
                nums[left] = nums[right];
                right++;
            }
        }
        return left + 1;
    }
}